package config

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
)

var ViperConfig viper.Viper

var AppConfig = ApplicationConfig{
	Server: Server{
		Ip:   "127.0.0.1",
		Port: 8899,
	},
	Mysql: Mysql{
		Url: "root:root@tcp(localhost:3306)/haiqiu_admin?charset=utf8&loc=%s&parseTime=true",
	},
	Config: TokenConfig{
		Token: Token{Secret: "secret"},
	},
	Accept: Accept{
		Urls: []string{"/captcha/", "/captcha", "/login", "/system/theme"},
	},
	Logger: Logger{
		Urls: []string{"/user/avatar", "/file/theme/upload"},
	},
	Http: ResourceHttp{
		Server:  "http://localhost:8899",
		Parent:  "./resource",
		Virtual: "/resource/",
	},
}

type ApplicationConfig struct {
	Server Server       `yaml:"server"`
	Mysql  Mysql        `yaml:"mysql"`
	Config TokenConfig  `yaml:"config"`
	Accept Accept       `yaml:"accept"`
	Logger Logger       `yaml:"logger"`
	Http   ResourceHttp `yaml:"http"`
}

type Server struct {
	Ip   string `yaml:"ip"`
	Port int    `yaml:"port"`
}

type Mysql struct {
	Url string `yaml:"url"`
}

type TokenConfig struct {
	Token Token `yaml:"token"`
}

type Token struct {
	Secret string `yaml:"secret"`
}

type Accept struct {
	Urls []string `yaml:"urls"`
}
type Logger struct {
	Urls []string `yaml:"urls"`
}

type ResourceHttp struct {
	Server  string `yaml:"server"`
	Parent  string `yaml:"parent"`
	Virtual string `yaml:"virtual"`
}

func init() {
	defer func() {
		if e := recover(); e != nil {
			switch v := e.(type) {
			case error:
				log.Println(v.Error())
			default:
				log.Println(e.(string))
			}
			log.Println("未找到自定义application.yaml配置，将加载默认配置")
		}
	}()
	v := viper.New()
	// 设置配置文件的名字
	v.SetConfigName("application")
	// 设置配置文件的类型
	v.SetConfigType("yaml")
	// 添加配置文件的路径，指定 config 目录下寻找
	v.AddConfigPath("./config")
	// 寻找配置文件并读取
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
	ViperConfig = *v
	//转化为结构体
	err = v.Unmarshal(&AppConfig)
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
}
